//only use manually
/*
function getConfigFromRyanAPI(DATA){
    var l = DATA.Fields.length;
    var fff = {};
    for (var i = 0; i < l; i++) {
        fff[DATA.Fields[i].Code] = {
            Name: DATA.Fields[i].Name,
            Option: DATA.Fields[i].Option,
        }
    }
    return fff;
}
*/
var QS_SearchOptions = {
    "OS010": {
        "Name": "Security Type",
        "Option": [{
            "txt": "Equity",
            "val": "ST"
        }, {
            "txt": "ETF",
            "val": "FE"
        }]
    },
    "LA03Z": {
        "Name": "Sector",
        "Option": [{
            "txt": "Any",
            "val": ""
        }, {
            "txt": "Basic Materials",
            "val": "101"
        }, {
            "txt": "Consumer Cyclical",
            "val": "102"
        }, {
            "txt": "Financial Services",
            "val": "103"
        }, {
            "txt": "Real Estate",
            "val": "104"
        }, {
            "txt": "Consumer Defensive",
            "val": "205"
        }, {
            "txt": "Healthcare",
            "val": "206"
        }, {
            "txt": "Utilities",
            "val": "207"
        }, {
            "txt": "Communication Services",
            "val": "308"
        }, {
            "txt": "Energy",
            "val": "309"
        }, {
            "txt": "Industrials",
            "val": "310"
        }, {
            "txt": "Technology",
            "val": "311"
        }]
    },
    "OS01V": {
        "Name": "Exchange Country",
        "Option": [{
            "txt": "Any",
            "val": ""
        }, {
            "txt": "United States",
            "val": "USA"
        }, {
            "txt": "Canada",
            "val": "CAN"
        }, {
            "txt": "United Kingdom",
            "val": "GBR"
        }]
    },
    "RR01Y": {
        "Name": "Morningstar Rating Overall",
        "Option": [{
            "txt": "1",
            "val": "1"
        }, {
            "txt": "2",
            "val": "2"
        }, {
            "txt": "3",
            "val": "3"
        }, {
            "txt": "4",
            "val": "4"
        }, {
            "txt": "5",
            "val": "5"
        }]
    },
    "ST159": {
        "Name": "Market Cap",
        "Option": [{
            txt: 'Any',
            val: ''
        }, {
            txt: '10 bil',
            val: '10000-99999'
        }, {
            txt: '5 bil',
            val: '5000-10000'
        }, {
            txt: '1 bil',
            val: '1000-5000'
        }, {
            txt: '500 mil',
            val: '500-1000'
        }, {
            txt: '250 mil',
            val: '250-500'
        }]
    },
    "HS05A": {
        "Name": "Equity Style Box (Long)",
        "Option": [{
            "txt": "Any",
            "val": ""
        }, {
            "txt": "Blend",
            "val": "2,5,8"
        }, {
            "txt": "Growth",
            "val": "3,6,9"
        }, {
            "txt": "Large",
            "val": "1,2,3"
        }, {
            "txt": "Large Blend",
            "val": "2"
        }, {
            "txt": "Large Growth",
            "val": "3"
        }, {
            "txt": "Large Value",
            "val": "1"
        }, {
            "txt": "Mid",
            "val": "4,5,6"
        }, {
            "txt": "Mid Blend",
            "val": "5"
        }, {
            "txt": "Mid Growth",
            "val": "6"
        }, {
            "txt": "Mid Value",
            "val": "4"
        }, {
            "txt": "Small",
            "val": "7,8,9"
        }, {
            "txt": "Small Blend",
            "val": "8"
        }, {
            "txt": "Small Growth",
            "val": "9"
        }, {
            "txt": "Small Value",
            "val": "7"
        }, {
            "txt": "Value",
            "val": "1,4,7"
        }]
    },
    "LS01Z": {
        "Name": "XI_Exchange",
        "Option": [{
            "txt": "Any",
            "val": ""
        }, {
            "txt": "NASDAQ",
            "val": "EX$$$$XNAS"
        }, {
            "txt": "LONDON STOCK EXCHANGE, THE",
            "val": "EX$$$$XLON"
        }]
    },
    "LI021": {
        "Name": "XI_Asset Class",
        "Option": [{
            "txt": "Any",
            "val": ""
        }, {
            "txt": "Stock",
            "val": "0"
        }, {
            "txt": "Corp/Govt Bond",
            "val": "1"
        }, {
            "txt": "Muni Bond",
            "val": "2"
        }, {
            "txt": "Alternative Investment",
            "val": "3"
        }, {
            "txt": "Asset Allocation/Target",
            "val": "4"
        }, {
            "txt": "Commodity",
            "val": "5"
        }, {
            "txt": "Derivatives",
            "val": "6"
        }, {
            "txt": "Economics",
            "val": "7"
        }, {
            "txt": "Money Market Rate",
            "val": "8"
        }]
    },
    "LS05M": {
        "Name": "XI_Base Currency",
        "Option": [{
            "txt": "Any",
            "val": ""
        }, {
            "txt": "US Dollar",
            "val": "USD"
        }, {
            "txt": "Canadian Dollar",
            "val": "CAD"
        }, {
            "txt": "Euro",
            "val": "EUR"
        }]
    },
    "IS020": {
        "Name": "XI_Country",
        "Option": [{
            "txt": "Any",
            "val": ""
        }, {
            "txt":"USA",
            "val": "USA"
        }, {
            "txt":"CAN",
            "val": "CAN"
        }]
    },
    "LI022": {
        "Name": "XI_Return Type",
        "Option": [{
            "txt": "Any",
            "val": ""
        }, {
            "txt":"Total Return",
            "val": "0"
        }, {
            "txt": "Price Return",
            "val": "1"
        }, {
            "txt": "Income Return",
            "val": "2"
        }, {
            "txt": "Flow",
            "val": "4"
        }, {
            "txt": "Market Value",
            "val": "5"
        }, {
            "txt": "Population",
            "val": "6"
        }, {
            "txt": "Yield",
            "val": "7"
        }]
    }
};
var RTQ_SearchDialog = function(domId, closeCallBack){
    this.mod;
    this.iptkw;
    this.gridDom;
    this.gridDt;
    this.ddlSecurityType;
    this.ddlCountry;
    this.ddlExchange;
    this.btnClose;
    this.mainTab = null;
    this.subTab = null;
    this.filterTabs = {};
    this.srhTimer = null;
    this.srhDelay = 200;
    this.closeCallBack = closeCallBack || function(){};
    this.html = '<div class="hd"><div class="filters"><div class="keyword"><h3>Keywords or Symbols</h3><input type="text" class="qs-ui-ipt" value=""></div><div class="cusip"><h3>CUSIP</h3><input type="text" class="qs-ui-ipt" value=""></div></div><div class="tabs"></div><div class="sub-tabs"></div></div><div class="bd"><div class="loading"></div><div class="rtsrh-grid"></div><div class="rtsrh-act"><a class="qs-ui-btn rtsrh-close-btn" href="javascript:void(0)">Close</a><strong>Drag-and-drop securities onto windows</strong></div></div>';
    this.filterG1Html = '<div class="boxwrap clearfix"> <div class="box"><h3>Country</h3><div class="ctn clearfix"></div></div><div class="box"><h3>Sector</h3><div class="ctn clearfix"></div></div> </div>' +
    '<div class="boxwrap clearfix"> <div class="box"><h3>Min Market Cap</h3><div class="ctn clearfix"></div></div><div class="box"><h3>Equity Style Box</h3><div class="ctn clearfix"></div></div> </div>' +
    '<div class="box"><h3>Star rating</h3><div class="ctn radio"></div></div>';
    this.filterG2Html = '<div class="boxwrap clearfix"> <div class="box"><h3>Country</h3><div class="ctn clearfix"></div></div><div class="box"><h3>Exchange</h3><div class="ctn clearfix"></div></div> </div>' +
    '<div class="boxwrap clearfix"> <div class="box"><h3>Return Type</h3><div class="ctn clearfix"></div></div><div class="box"><h3>Asset Class</h3><div class="ctn clearfix"></div></div> </div>' +
    '<div class="box"><h3>Base Currency</h3><div class="ctn radio"></div></div>';
    
    this.points = {
        'Name': {code:'OS01W',txt:'Name'},
        'CUSIP': {code:'OS05K',txt:'CUSIP'},
        'Symbol': {code:'OS001',txt:'Symbol'},
        'Type': {code:'OS010',txt:'Type'},
        'Country': {code:'OS01V',txt:'Country', align:'center'},
        'Market Cap': {code:'ST159',txt:'Market Cap', width:80},
        'Exchange': {code:'OS01X',txt:'Exchange', width:80},
        'Sector': {code:'LA03Z',txt:'Sector', width:100},
        'Style Box': {code:'HS05A',txt:'Style Box', width:80},
        'Rating': {code:'RR01Y',txt:'Rating', width:120},
        'PID': {code:'OS06Y',txt:'PID'},
        'XI_Country': {code:'IS020',txt:'Country', width:80, align:'center'},
        'XI_Exchange': {code:'LS01Z',txt:'Exchange', width:80},
        'XI_Ticker': {code:'OS385',txt:'Ticker', width:80},
        'XI_Return Type': {code:'LI022',txt:'Return Type', width:80, align:'center'},
        'XI_Asset Class': {code:'LI021',txt:'Asset Class', width:90, align:'center'},
        'XI_Base Currency': {code:'LS05M',txt:'Base Currency', width:80, align:'center'},
        'XI_Firm Name': {code:'OF006',txt:'Firm Name', width:120}

    };
    this.returnMapping = {};
    this.init(domId);
};

RTQ_SearchDialog.prototype = {
    init: function(id){
        var self = this;
        this.mod = $('#' + id).html(this.html);
        this.loading = this.mod.find('.bd>.loading');
        this.iptkw = this.mod.find('.keyword input').keyup(function(e){
            self.search.call(self);
        }).focus(function(){
            $(this).select();
        });
        this.cusipDom=this.mod.find('.cusip');
        this.iptcusip = this.cusipDom.find('input').keyup(function(e){
            self.search.call(self);
        }).focus(function(){
            $(this).select();
        });
        this.btnClose = this.mod.find('.rtsrh-close-btn');
        this.btnClose.click(function(){
            self.closeSearchDlg();
        })
        
        this.mainTab = new Util.TabMenu(this.mod.find('.hd .tabs')[0], [{
            txt: 'Equities',
            id: 'ST',
            closable: false
        }, {
            txt: 'Indexes',
            id: 'XI',
            closable: false,
            disabled: false
        }], {
            onActive: function(tab){
                if (!self.filterTabs[tab.id]) {
                    switch (tab.id) {
                        case 'ST':
                            if(QSPC.checkPermission(29.01)){
                                self.cusipDom.show();
                            }else{
                                self.cusipDom.hide();
                            }
                            self.buildSTFilter(tab);
                            break;
                        case 'XI':
                            self.cusipDom.hide();
                            self.buildXIFilter(tab);
                            break;
                    }
                }
                else {
                    if(tab.id=="ST"&&QSPC.checkPermission(29.01)){
                        self.cusipDom.show();
                    }else{
                        self.cusipDom.hide();
                    }
                    self.grid.empty();
                }
                self.search();
            }
        }, {
            isExcuteCallbackAtInit: true
        });
        /*
        this.subTab = new Util.TabMenu(this.mod.find('.hd .sub-tabs')[0], [{
            txt: 'Equities',
            id: '1',
            closable: false
        }], {});
        */
       
        for (var k in QS_SearchOptions) {
            this.returnMapping[k] = {};
            for (var i = 0; i < QS_SearchOptions[k].Option.length; i++) {
                this.returnMapping[k][QS_SearchOptions[k].Option[i].val] = QS_SearchOptions[k].Option[i].txt;
            }
        }
        this.gridDom = this.mod.find('.rtsrh-grid')[0];
        this.createGrid();
    },
    showLoading: function(){
        this.mod.addClass('srh-loading');
    },
    hideLoading: function(){
        this.mod.removeClass('srh-loading');
    },
    buildSTFilter: function(tab){
        var self = this;
        this.filterTabs['ST'] = new Util.TabMenu(tab.panel, [{
            txt: 'Basic',
            id: '1',
            closable: false
        }], {}, {
            tabsList: false,
            vertical: true
        });
        
        this.filterTabs['ST'].tabs[0].panel.append(this.filterG1Html);
        var filterBoxs = this.filterTabs['ST'].tabs[0].panel.find('.box>.ctn');
        
        this.ddlCountry = new Util.DropDownList(filterBoxs.eq(0), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['Country'].code].Option, {
            width: 130,
            actionAtInit: false
        });
        
        this.ddlSector = new Util.DropDownList(filterBoxs.eq(1), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['Sector'].code].Option, {
            width: 130,
            actionAtInit: false
        });
        this.ddlMinMarketCap = new Util.DropDownList(filterBoxs.eq(2), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['Market Cap'].code].Option, {
            width: 130,
            actionAtInit: false
        });
        this.ddlEquityStyleBox = new Util.DropDownList(filterBoxs.eq(3), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['Style Box'].code].Option, {
            width: 130,
            actionAtInit: false
        });
        
        //radion btn
        this.starRatingCBtn = new Util.ButtonGroup(filterBoxs.eq(4), QS_SearchOptions[this.points['Rating'].code].Option, {
            onClick: function(v){
                self.search();
            }
        });
    },
    buildXIFilter: function(tab){
        var self = this;
        this.filterTabs['XI'] = new Util.TabMenu(tab.panel, [{
            txt: 'Basic',
            id: '1',
            closable: false
        }], {}, {
            tabsList: false,
            vertical: true
        });
        
        this.filterTabs['XI'].tabs[0].panel.append(this.filterG2Html);
        var filterBoxs = this.filterTabs['XI'].tabs[0].panel.find('.box>.ctn');
        
        this.ddlCountryXI = new Util.DropDownList(filterBoxs.eq(0), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['XI_Country'].code].Option, {
            width: 130,
            actionAtInit: false
        });
        this.ddlExchangeXI = new Util.DropDownList(filterBoxs.eq(1), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['XI_Exchange'].code].Option, {
            width: 130,
            actionAtInit: false
        });
        this.ddlReturnTypeXI = new Util.DropDownList(filterBoxs.eq(2), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['XI_Return Type'].code].Option, {
            width: 130,
            actionAtInit: false
        });
        this.ddlAssetClassXI = new Util.DropDownList(filterBoxs.eq(3), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['XI_Asset Class'].code].Option, {
            width: 130,
            actionAtInit: false
        });
        this.ddlBaseCurrencyXI = new Util.DropDownList(filterBoxs.eq(4), function(t, v){
            self.search();
        }, QS_SearchOptions[this.points['XI_Base Currency'].code].Option, {
            width: 130,
            actionAtInit: false
        });

    },
    getDataCols:function(addCols){//common fiter
        var col=[],name=null,defaultcols=["Name"];
        for(var i=0,l=defaultcols.length;i<l;i++){
            name=defaultcols[i];
            col.push({
                header: name,
                width: name=="Name"?180:80,
                dataIndex: this.points[name].code
            });
        }
        return addCols?col.concat(addCols):col;
    },
    search: function(){
        var self = this;
        if (this.srhTimer) {
            clearTimeout(this.srhTimer);
            this.srhTimer = 0;
        }
        this.srhTimer = setTimeout(function(){
            self.getData();
        }, this.srhDelay);
    },
    closeSearchDlg: function(e){
        this.closeCallBack()
    },
    createGrid: function(){
        var self = this;
        this.grid = new Util.DataGrid(this.gridDom, {}, {
            column: this.getDataCols(),
            indexColKey: this.points['PID'].code,
            width: 450,
            height: 245,
            htmlLayer: 'div',
            rowDragable: true,
            //cellResize: false,
            rowDragDropGroup: 'gridDDGroup'
        }, {
            onRowRemove: function(id, row){
                self._removeSymbol(id);
            },
            onRowDragStart: function(e, proxy, row){
                proxy._ticker = row.id;
                proxy.html(row.cells[self.points['Name'].code].el.html());
            },
            onRowRearrange: function(row, insertbeforerow){
                //self._rearrangeTickers(row.id, insertbeforerow.id);
            }
        });
    },
    refreshGrid: function(data){
        this.gridDt = data;
        this.grid.reBindData(this.gridDt);
        //this.grid.getColumnModel().setHidden(4, true);
    },
    _getDefaultCols:function(){
        var returnKeys = [];
        switch(this.mainTab.currentTab.id){
            case 'ST':
                returnKeys =QSPC.checkPermission(29.01)?['Symbol','CUSIP', 'PID']:['Symbol','PID'];
                break;
            case 'XI':
                returnKeys = ['XI_Ticker','PID','XI_Firm Name'];
                break;
            
        }
        return returnKeys;
    },
    getData: function(){
        var self = this;
        var filter = [];
        var returnKeys = this._getDefaultCols();
        var returnCols = [];
        var cols = [];
        // add def cols
        for (var i = 0; i < returnKeys.length; i++) {
            returnCols.push(this.points[returnKeys[i]].code);
            cols.push({
                header: this.points[returnKeys[i]].txt,
                dataIndex: this.points[returnKeys[i]].code,
                hide: returnKeys[i]=="PID"?true:false
            });
        }
        
        
        var addFilter = function(pointKey, val, type, opt, maxVal, include){
			returnCols.push(self.points[pointKey].code);
            if (val && val != '') {
                var d = {
                    Name: self.points[pointKey].code,
                    Type: type || 1, //1:equals/2:between/3:in
                    TextOperator: opt || 1, //1:exact/2:startwith
                    Value: val
                };
                if(type == 2){
                    d.IsInclude = include;
                    d.MinValue = val;
                    d.MaxValue = maxVal;
                    delete d.Value;
                }
                if (type == 3) {
                    d.IsInclude = true;
                }
                filter.push(d);
                
                if (pointKey!='CUSIP'&&pointKey!='Name'&&pointKey!='Type') { //datagrid cols
                    var renderer = null;
                    switch(pointKey){
                        case 'Style Box':
                        case 'Sector':
                        case 'XI_Exchange':
                        case 'XI_Return Type':
                        case 'XI_Asset Class':{
                            renderer = function(v){
                                for(var k in self.returnMapping[self.points[pointKey].code]){
                                    if(k==v){
                                        return self.returnMapping[self.points[pointKey].code][k];
                                    }
                                }
                                return v;
                            }
                        }break;
                        case 'Market Cap':{
                            renderer = function(v){
                                return v?parseFloat(v).toFixed(2) + ' mil':'';
                            }
                        }break;
                    }
                    cols.push({
                        header: self.points[pointKey].txt,
                        dataIndex: self.points[pointKey].code,
                        width: self.points[pointKey].width,
                        align: self.points[pointKey].align,
                        renderer: renderer
                    });
                    
                }
            }
        };
        
        
        switch (this.mainTab.currentTab.id) {
            case 'ST':
                addFilter('Name', this.iptkw.val(), 1, 2);
                addFilter('CUSIP', this.iptcusip.val(), 1, 2);
                addFilter('Type', this.mainTab.currentTab.id,3);
                addFilter('Country', this.ddlCountry.getValue(),3);
                //addFilter('Sector', this.ddlSector.getValue());
                addFilter('Sector', this.ddlSector.getValue(), 3);
                addFilter('Style Box', this.ddlEquityStyleBox.getValue(), 3);
                addFilter('Rating', this.starRatingCBtn.getValue()[0], 3);
                addFilter('Market Cap', this.ddlMinMarketCap.getValue().split('-')[0], 2, 1, this.ddlMinMarketCap.getValue().split('-')[1], true);
                
                break;
            case 'XI':
                addFilter('Name', this.iptkw.val(), 1, 2);
                addFilter('Type', this.mainTab.currentTab.id,3);
                addFilter('XI_Country', this.ddlCountryXI.getValue(),3);
                addFilter('XI_Exchange', this.ddlExchangeXI.getValue(),3);
                addFilter('XI_Return Type', this.ddlReturnTypeXI.getValue(), 3);
                addFilter('XI_Asset Class', this.ddlAssetClassXI.getValue(), 3);
                addFilter('XI_Base Currency', this.ddlBaseCurrencyXI.getValue(),3);
                break;
        }
        
        //dont search if not any fliter
        if (filter.length>1) {//Type is default
            this.showLoading();
            $.post('advancedSearch.jsp', {
                query: $.toJSON({
                    Keywords: filter,
                    SecType: this.mainTab.currentTab.id
                }),
                start: 0,
                col: $.toJSON({
                    Columns: returnCols
                })
            }, function(o){
                //alert(o);
                o = $.evalJSON(o);
                self.grid.setColumnCfg(self.getDataCols(cols));
                self.refreshGrid(o.Columns);
                self.hideLoading();
            });
        }
    }
}
